<?php
/*
自定义函数大全
@author yhbhiron
*/

/**字符处理类**/

if(!defined('IN_WEB')){
	exit('Access Deny!');
}

/**
中文下Gb2312编码的字符截取
@param $str string 要截取的字符串
@param start int 开始位置
@param len int 长度
**/

function subStrGB($str,$start,$len){
	
	$strlen=$start+$len;
	for($i=0;$i<$strlen;$i++)
	{
		if(ord(substr($str,$i,1))>0xa0)
		{
			$tmpstr.=substr($str,$i,2);
			$i++;
		}
		else
		{
			if($i>=$start)
			{
				$tmpstr.=substr($str,$i,1);
			}
		 }
	}
	return  $tmpstr;	
	
	
}
/**
计算字符串的个数GB2312编码
@param $str string 计算的字符
@return 计算出的个数
**/
function strCount($str){
	$len=0;
	for($i=0;$i<=strlen($str);$i++){
		if(ord(substr($str,$i,1))>0xa0){
			$i++;
		}
		$len++;
	}
	return $len-1;
}


/**
中文下utf编码的字符截取
@param $str string 要截取的字符串
@param start int 开始位置
@param len int 长度
**/
function subStrUTF($str,$start,$length,$after=''){
	
	if(!isset($str{$start})) return $str;
	
	if(!isset($str{$length})) return $str;
	
	$str = iconv('utf-8','gbk',$str);
	return iconv('gbk','utf-8',subStrGB($str,$start,$length));
	
}




/**
计算字符串的个数utf8编码
@param $str string 计算的字符
@return 计算出的个数
**/
function strCountUTF($str){
	$len=0;
	for($i=0;$i<=strlen($str);$i++){
		if(ord(substr($str,$i,1))>0xa0){
			$i+=2;
		}
		$len++;
	}
	return $len-1;
}


function stripLast($str,$strip){
	
	if($str == '') return;
	
	$stripLen = strlen($strip);
	
	return substr($str,0,0-$stripLen);

}

function stripFirst($str,$strip){
	
	if($str == '') return;
	
	$stripLen = strlen($strip);
	
	return substr($str,$stripLen);

}

function addStrRight($str,$add){
	
	if($add == substr($str,-1,1)){	
		
		return $str;
	}
	
	return $str.$add;
}


function addCharLR($str,$add){
	return $add.$str.$add;
}

//去掉\
function hStripSlashes($string, $force =0) {

	if(is_array($string)) {
		foreach($string as $key => $val) {
			$string[$key] = stripslashes($val, $force);
		}
	} else {
		$string = stripslashes($string);
	}
	
	return $string;
}

//转换html代码,$str为字符串
function toSafeHtml($str){
	if(is_array($str)){
		foreach($str as $key=>$value){
			$new[$key]=toSafeHtml($value);
		}
	}else{
		$new=htmlspecialchars($str);
	}
	return trim($new);
}

function isnotEmptyHtml($code){
	
	return ($code!='' && (strip_tags($code)=='' && preg_match('/<img/i',$code))) || ($code!='' && strip_tags($code)!='');
}

//过滤gpc
function haddslashes($string, $force =0) {
	!defined('MAGIC_QUOTES_GPC') && define('MAGIC_QUOTES_GPC', get_magic_quotes_gpc());
	if(!MAGIC_QUOTES_GPC || $force) {
		if(is_array($string)) {
			foreach($string as $key => $val) {
				$string[$key] = haddslashes($val, $force);
			}
		} else {
			$string = addslashes($string);
		}
	}
	return $string;
}


/**
 * 设定默认值
 * @param string $val -需要判断的值
 * @param string $def  -设定的默认值
 * @param string $case 特殊比较的值
 * 
 */
function defVal($val,$def,$case=''){

	if($case!=''){
		if($val!=$case){
			return $def;
		}
	}
	
	if($val==''){
		return $def;
	}
	
	return $val;
	
	
}

/**
 * 去除代码的html代码
 * @param string $html;
 * return string 去除的代码
 */
function clearScript($html){
	$html=preg_replace('/<script.*>(.+?)<\/script>/is','',$html);
	return $html;
}

function isBase64($string) {
	
	$strlen=strlen($string);
	if($strlen%4==0){
		
			return $string == base64_encode(base64_decode($string));
			
	}else{
	   return false;
	}
} 



/*
盐式加密
*/
function saltEncode($pwd,$sec=''){
		
	if($sec=='' && !defined('SYS_SEC')){
		
		return false;	
	}
	
	$sec = $sec == '' ? SYS_SEC : $sec;
	return md5($sec.$pwd.$sec);
	
}

function shaEncode($pwd,$sec=''){
		
	if($sec=='' && !defined('SYS_SEC')){
		
		return false;	
	}
	
	$sec = $sec == '' ? SYS_SEC : $sec;
	return sha1($sec.$pwd.$sec);
	
}
/**
随机字符
@param int len 字符长度
@param string $type 值Num数字,Lower小写字母,Upper大写字母,Mixed混合
@param time 是加时间
@return string 字符
**/
function randStr($len=8,$type='Num',$time=true){
	if($type=='Num'){
		$rand='1342507869';
	}else if($type=='Lower'){
		$rand='abcdefghijklmnopqrstuvwxyz';
	}else if($type=='Upper'){
		$rand='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	}else if($type=='Mixed'){
		$rand='01jPUklm!o2QT3ac4eGHpGKL_Mq67hiDE@8r-RSstVu59vwW+XzABCxdyFbIfgNOYZ';
	}
	$len=intval($len);
	for($i=1;$i<=$len;$i++){
		$str.=substr($rand,rand(0,strlen($rand)-1),1);
	}
	$str=$time==true ? $str.date('YmdHis') : $str;
	return $str;
}


/**
将字符转换成数据库段字符
@param array $arr 要转化的数组
@param string 要转化的类型 sys为系统的serialize函数,其它为字符隔开
*/
function toDataArray($arr,$spe='sys'){
	
	if($arr==null || !is_array($arr)){
		return false;
	}
	
	if($spe == 'sys'){
		
		return serialize($arr);	
	}else{
		return implode($spe,$arr);
	}
}

/*
将字符转成为数组
@param string $str 需要转化的数组
@param string $spe 转化类型
*/
function dataStrArray($str,$spe='sys'){
	
	if($str==null || $str==''){
		return false;	
	}
	
	if($spe == 'sys'){
		return @unserialize($arr);	
	}else{
		
		
		if(strstr($str,$spe)){
			$temp = array();
			$temp = explode($spe,$str);
		}else{
			$temp = array($str);	
		}
		return $temp;
	}
	
	
}

/**
 * 计算某一数据库查询数组的指定字段的和
 * @param array $data -array(0=>array(),1=>array(),...)数组类别
 * @return array();
 */
function dataArraySum($data){
	
	if(!is_array($data) || $data==null){
		return;	
	}
	
	$newArray = array();
	foreach($data as $k=>$per){
		foreach($per as $fld=>$val){
			if(is_numeric($val)){
				$newArray[$fld]+=$val;
			}
		}	
	}
	
	return $newArray;
}

/*
 * 修改字符串数组
 * @param string $str 数组导出的字符串
 * @parma string $val 要删除或添加的字符
 * @param string $do 操作类型 delete or add
 * @param string $spe 生成类型 或分隔类型
 */
function modifyDataStrArr($str,$val,$do,$spe='sys'){
	
	$data = dataStrArray($str,$spe);
	if(!$data || $data==null){
		$data = array();
	}
	
	if($do == 'delete' && $data!=null){
		foreach($data as $k=>$v){
			
			if($v == $val){
				unset($data[$k]);
				break;
			}
		}
		
		return toDataArray($data,$spe);
	}else if($do == 'add'){
		
		if(!in_array($val,$data)){
			$data[] = $val;	
		}
		
		return toDataArray($data,$spe);
	}
	
}

/*
 * 转换url地址为正则表达式
 */
function URLRegExpStr($str){
	
	if($str==null || $str==''){
		return;
	}
	
	$str = preg_quote($str);
	$str = preg_replace('/\d+/','\d+',$str);
	$str = str_replace('\|','|',$str);
	
	$str = '/^'.$str.'/';
	return $str;
}


/**系统类**/


/*取得路径
 * 返回 数组
		 $addr_arr['page'] 当前地址，无参数
		 $addr_arr['url'] 当前地址，有参数
		 $addr_arr['script'] 当前脚本名，无参数
		 $addr_arr['basename'] 当前脚本名,有参数
		 $addr_arr['from'] 来源地址
* **/
function getAddr(){
	$addr_arr  = array();
	$cur_addr   = substr($_SERVER['SCRIPT_NAME'],strpos($_SERVER['SCRIPT_NAME'],'/'));
	$addr_arr['host']=realpath(ROOT)!=realpath($_SERVER['DOCUMENT_ROOT']) ? 'http://'.$_SERVER['HTTP_HOST'].'/'.basename(ROOT).'/' : 'http://'.$_SERVER['HTTP_HOST'].'/' ;
	//$addr_arr['host']='http://'.$_SERVER['HTTP_HOST'].'/hos/';
	$addr_arr['page']  = 'http://'.$_SERVER['HTTP_HOST'].$cur_addr;
	$addr_arr['url'] = !empty($_SERVER['QUERY_STRING']) ? $addr_arr['page'].'?'.$_SERVER['QUERY_STRING']: $addr_arr['page'];
	$addr_arr['script']=substr($_SERVER['PHP_SELF'],strrpos($_SERVER['PHP_SELF'],'/')+1,strlen($_SERVER['PHP_SELF'])-strrpos($_SERVER['PHP_SELF'],'/'));

	$cur_url=substr($_SERVER['HTTP_REFERER'],strrpos($_SERVER['HTTP_REFERER'],'/')+1,strlen($_SERVER['HTTP_REFERER'])-strrpos($_SERVER['HTTP_REFERER'],'/'));
	$addr_arr['basename']=!empty($_SERVER['QUERY_STRING']) ? $addr_arr['script'].'?'.$_SERVER['QUERY_STRING']: $addr_arr['script'];
	$addr_arr['from'] =$_SERVER['HTTP_REFERER']!='' ? $_SERVER['HTTP_REFERER'] : '';
	$addr_arr['path_url'] = substr($addr_arr['url'],strlen($addr_arr['host']));
	$addr_arr['path'] = substr($addr_arr['page'],strlen($addr_arr['host']));
	return $addr_arr;
}

/*
获取用户的浏览器类型
*/
function getBrowser(){
	
	$agent = $_SERVER["HTTP_USER_AGENT"];
	if(strstr($agent,'MSIE 6.0')){
		return 'ie6';
	}else if(strstr($agent,'MSIE 7.0')){
		return 'ie7';
	}else if(strstr($agent,'MSIE 8.0')){
		return 'ie8';
	}else if(strstr($agent,'Firefox/3')){
		return 'ff3';
	}else if(strstr($agent,'Firefox/2')){
		return 'ff2';
	}else if(strstr($agent,'Firefox/4')){
		return 'ff4';
	}else if(strstr($agent,'Firefox/5')){
		return 'ff5';		
	}else if(strstr($agent,'Chrome')){
		return 'chrome';
	}else if(strstr($agent,'Safari')){
		return 'safari';
	}else if(strstr($agent,'Opera')){
		return 'opera';
	}
}

/*
gizp压缩输出
请不要在程序中使用flush，否则将会出现乱码
*/
function obGzip($content)
{   


	header('Content-type:text/html;charset='.SYS_CHARSET);
	header('Content-Language:cn');	

	if( USE_GZIP && extension_loaded("zlib") && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip"))
    {
        $content = gzencode($content,9);
		header('Connection:keep-alive');
		header("Content-Encoding: gzip");//zip压缩
        header("Vary: Accept-Encoding");//代理缓存
        header("Content-Length: ".strlen($content));//设置压缩大小
    }
	
	if(DEBUG){
		$GLOBALS['debugStr'][] = '页面大小:'.bitsToMb(strlen($content));
	}
	
    return $content;
}

function inject_check($sql_str) {
	return eregi('select|insert|update|delete|\'|\/|load_file|outfile', $sql_str);    // 进行过滤
}

function debugAdd($str){
	if(DEBUG){
		if(!is_object($str) && !is_resource($str) && !is_array($str)){
			$GLOBALS['debugStr'][] = '<font color=blue>'.strval($str).'</font>';
		}else{
			$GLOBALS['debugStr'][] = '<font color=blue>'.var_export($str,true).'</font>';
		}
	}
}

/*加入调试信息*/
function debugWrite(){
	if(DEBUG == true){
		global $debugStr,$addr;
		
		$sysRunEndTime = run_time();
		$debugStr[] =  '<font color=green>SQL执行时间:'.$GLOBALS['sql_time'].' ms</font>';
		$debugStr[] = '<font color=green>页面执行时间:'.(($sysRunEndTime - $GLOBALS['sysRunStartTime'])*1000).' ms</font>';
		$debugStr[] = 'PHP版本:'.PHP_VERSION.'；系统根目录:'.ROOT.'; OS:'.PHP_OS.'; '.'主机:'.$addr['host'].'; 当前模板目录:'.realpath(TEMPLE_DIR);
		$debugStr[] = '当前文件：'.$addr['page'];
		$debugStr[]  = '可用内存：'.ini_get('memory_limit').'; 内存使用：'.round(bitsToMb(memory_get_usage()),2).'M';
		$debugStr[]  = 'POST:'.toSafeHtml(var_export($_POST,true));
		$debugStr[]  = 'GET:'.toSafeHtml(var_export($_GET,true));
		$debugStr[]  = 'SESSION:'.toSafeHtml(var_export($_SESSION,true));
		
		
		$inc = get_included_files();
		$incFiles = '引用文件:'.count($inc).'<br />';
		if($inc!=null){
			$incFiles.=toDataArray($inc,'<br />');
		}
		$debugStr[] = $incFiles;
		
		$vars = get_defined_vars();
		//$debugStr[] = '<font color=brown>使用变量:<br />'.nl2br(var_export($vars,true)).'</font>';
		
		
		if($debugStr!=null && is_array($debugStr)){
			echo '<h4>调试信息</h4>';
			foreach($debugStr as $k=>$str){
				
				echo '<p>'.($k+1).'. <font color=red>'.$str.'</font></p>';	
			}
			
		}
	}
}

/**
 * 获取执行的调试信息，调试用
 *@return array;
 */
function getExecTracer(){
	try{
		throw new Exception('get excute line');
	}catch(Exception $e){
		$info = $e->getTrace();	
		$str = '';
		foreach($info as $k=>$err){
			$str.='<p>file: '.$err['file'].'; Line: '.$err['line'].'</p>';
		}
		return $str;
	}

}


/*
系统时间调试函数
*/
function run_time(){
	list($msec,$sec)=explode(' ',microtime());
	return ((float)$msec+(float)$sec);
}

function recordData($dataName,$data,$number){
	
	if($_SESSION[$dataName]!=null){
		
		if(count($_SESSION[$dataName])>=$number){

			$rate = array_sum($_SESSION[$dataName])/$number;
			session_unregister($dataName);
			unset($_SESSION[$dataName]);
			
			return $rate;
		}
		
		$_SESSION[$dataName][]=$data;
		
		return '剩于'.($number - count($_SESSION[$dataName])).'次';
		
	}else{
		
		$_SESSION[$dataName] = array();
		$_SESSION[$dataName][0] = $data;
		
		
	}
}

/** 
读取远程文件件
$url为一远程地址
**/
function GetRemoteFile($url){
	
		if($url==''){
			return false;
		}
		
		$ch = curl_init();		
		$timeout = 30; // set to zero for no timeout
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true); 
		curl_setopt($ch,CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.5.21022; .NET CLR 3.5.30729; .NET CLR 3.0.30729; AskTB5.4)");
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		$handles = curl_exec($ch);
		curl_close($ch);
		return $handles;
}
/*
重定向
*/
function redirect($url,$server=true)
{
	if($server){
		if(!@header("Location: $url")){
			exit("<script>window.location.href='$url'</script>");
		}
		exit;
	}else{
		exit("<script>window.location.href='$url'</script>");
	}
}
/*
返回
*/
function  back()
{
	exit("<script>window.history.back()</script>");

}
/** 
写入cookie
@param $ckey cookie的key值
@param string $cvalue 值
@para $expires 超时时间
@param string $unit d,h,m,s
@return 无 
**/
function setCookies($ckey,$cvalue,$expires=3,$unit='d'){

	$expires= !is_numeric($expires) ? 3:$expires;
	setcookie(PRE.$ckey,base64_encode($cvalue),dateSub(now(),$expires,$unit) );
}


/*
读取cookie,如果指定key则返回
对应的key的cookie值
@param $item string key值
@param string or array
*/
function readCookies($item=''){
	foreach($_COOKIE as $key=>$value){
		if(substr($key,0,strlen(PRE))==PRE){
			if($item!=''){
				
				if(substr($key,strlen(PRE))==$item){
					 $_hcookies=base64_decode($value);
					 break;
				}
			}else{
				$_hcookies[]=base64_decode($value);
			}
		}
	}
	return $_hcookies;

}


/*
清除指定key值的cookie
*/
function clearCookie($ckey){
	
	foreach($_COOKIE as $key=>$value){
		if(substr($key,0,strlen(PRE))==PRE){
			if($ckey!=''){
				setCookies($ckey,'',0,'s');
				return true;
			}
		}
	}
	
}

function getrobot() {
	if(!defined('IS_ROBOT')) {
		$kw_spiders = 'Bot|Crawl|Spider|slurp|sohu-search|lycos|robozilla';
		$kw_browsers = 'MSIE|Netscape|Opera|Konqueror|Mozilla';
		if(!strexists($_SERVER['HTTP_USER_AGENT'], 'http://') && preg_match("/($kw_browsers)/i", $_SERVER['HTTP_USER_AGENT'])) {
			define('IS_ROBOT', FALSE);
		} elseif(preg_match("/($kw_spiders)/i", $_SERVER['HTTP_USER_AGENT'])) {
			define('IS_ROBOT', TRUE);
		} else {
			define('IS_ROBOT', FALSE);
		}
	}
	return IS_ROBOT;
}

function getUserIp(){
	$ip_reg='/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/';
	if(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}elseif(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} 
	if(preg_match($ip_reg,$onlineip)){
		return $onlineip;
	}
}


/*
判断一个数组是不是另一个数组的子集,一维数组
array($v1,$v2);
@param array/string $ch;
@param array $subject;
*/
function arrInArray($ch,$subject){
	
	if($subject==null || !is_array($subject)){
		
		return false;
	}
	
	if($ch==null){
		return false;
	}
	
	if(is_array($ch)){
		
		foreach($ch as $k=>$v){
			
			if(!in_array($v,$subject)){
				return false;
			}
		}
	}
	
	return true;
}


/*
将数据库读取数组变为一维数组array($k=>$v);
@param array $arr 需要转化的数组
@param string $keyName 新数组中键值的来源键名
@param string $valName 新数组中值的来源键名
@return array 重组后的数组;
*/
function dataToOneArr($arr,$keyName,$valName){
	
	if(!is_array($arr) ||$arr == null){
		return array();	
	}
	
	$temp = array();
	foreach($arr as $k=>$value){
		
		if(!is_array($valName)){
			$temp[$value[$keyName]] = $value[$valName];
		}else{
			
			$valArray = array();
			foreach($valName as $vk=>$val){
				
				$valArray[$value[$vk]] = $value[$val];
			}
			
			$temp[$value[$keyName]] = $valArray;
			unset($valArray);
		}
	}
	
	return $temp;
}

/*
多用于数据库数据项过滤
去除子集中不符的项,适合二维数组
@param array $ch数据项 $fld=>$val
@param array $sub 数据字段表 $val;

*/
function stripNotMatch($ch,$sub){

	if(!is_array($ch) || $ch==null || !is_array($sub) || $sub==null){
	
		return null;

	}
	
	
	foreach($ch as $k=>$v){
	
		if(!in_array($k,$sub)){
		
			unset($ch[$k]);
		}
	}
	
	return $ch;
}

/*
保存一个变量到文件
@param string $varName 变量名称
@param mixed $var 变量
@param string 保存的文件名
@direct boolean 文件是否可以直接访问
*/

function saveVarsPhp($varName,$var,$file,$direct=true){
	
	if(!file_exists($file)){
		return false;	
	}
	$export = var_export($var,true);
	$const = $direct!=true ? "\nif(!defined('IN_WEB')){\n exit;\n}\n" : '';
	$code  = "<?php\n
	$const
	$varName = $export ;
	\n
	?>";
	
	file_put_contents($file,$code,LOCK_EX);
}


/*
导入动态配置项为常量
@param string $cfgFile 系统动态配置文件路径
*/
function loadConfig($cfgFile){
	
	if(!file_exists($cfgFile)){
		
		return false;	
	}
	
	require($cfgFile);
	if($webVarsConfig == null){
		return false;
	}
	
	foreach($webVarsConfig as $cfgName=>$cfgValue){		
		define($cfgName,$cfgValue['value']);	
	}
}

/*
返回默认值
@param string $newVal 新值
@param string $default 默认值
@param array $valueArray 充许值列表
*/
function setDefault($newVal,$default,$valueArray){
	
	if($valueArray==null || !is_array($valueArray)){
	
		return false;
	}
	
	if(!in_array($newVal,$valueArray)){
		return $default;
	}else{
		return $newVal;
	}

}

function remVal($key,$new=null,$time=60,$type='session'){
	
	if(!in_array($type,array('session','cookie'))){
		return false;						 
	}
	
	if($type == 'session'){
		
		if($new!=null && $new!=''){
			
			$_SESSION[$key] = $new;
			return $new;
		}
		
		if($_SESSION[$key]!='' || $_SESSION[$key]!=null	){
			
			return $_SESSION[$key];
		}
		
		
	}else if($type == 'cookie'){
		
		if($new!=null && $new!=''){
			
			setCookies($key,$new,$time,'s');
			return $new;
		}

		$old = readCookies($key);
		if($old!=null || $old!=''){
			return $old;
		}
	}
}


/*
 * 加载类库
 */
function loadClass($className){


	if(class_exists($className)){
		return;
	}	
	
	if(!file_exists(WEB_CLASS_DIR.$className.'.class.php')){
		if(class_exists('error') && is_object($GLOBALS['error'])){			
			$GLOBALS['error']->showErrorStr('加载的类库'.$className.'不存在!','javascript:history.back()',false);
		}else{
			throw new Exception('加载的类库'.$className.'不存在!');
		}		
	}
	

	
	if(DEBUG){
		$start = run_time();
	}
	$res = require(WEB_CLASS_DIR.$className.'.class.php');
	if(DEBUG){
		$end = run_time();
	}
	
	
	if(DEBUG){
		$GLOBALS['debugStr'][] ='加载类库'.$className.'<font color="green">(时间:'.(($end - $start)*1000).' ms)</font>';
	}
	
	return $res;
}


function webStart($app){

	if(DEBUG){
		$start = run_time();
	}
	if($app == '' || !file_exists(WEB_APP_DIR.$app.'.app.php')){
		$app = 'main';
		if($app == '' || !file_exists(WEB_APP_DIR.$app.'.app.php')){
		
			if(class_exists('error') && is_object($GLOBALS['error'])){			
				$GLOBALS['error']->showErrorStr('加载的模块'.$app.'不存在!','javascript:history.back()',false);
			}else{
				throw new Exception('加载的模块'.$app.'不存在!');
			}	
		}
	}


	
	include(WEB_APP_DIR.$app.'.app.php');	
	if(DEBUG){
		$end = run_time();
	}
	
	if(DEBUG){
		$GLOBALS['debugStr'][] = '加载应用'.$app.'<font color="green">(时间:'.(($end - $start)*1000).' ms)</font>';
	}
	
	if(!class_exists($app) || !method_exists($app,'run')){
		if(class_exists('error') && is_object($GLOBALS['error'])){			
			$GLOBALS['error']->showErrorStr($app.'不合法的应用!','javascript:history.back()',false);
		}else{
			throw new Exception('应用'.$app.'不合法!');
		}	
	
	}else{
		
		$excuteApp = new $app();
		$excuteApp->run();
	}
	

}


/*
上传文件，支持数组文件上传和单个文件上传
@param string $_file 文件字段名称
@param string $savePath
@param string $newName;
@param string $resizeKey重定义大小的键值
*/
function uploadFile($_file,$savePath,$newName=null,$resizeKey=null){
	global $allowFormat;
	
	if(!file_exists($savePath)){
		return '';
	}
	
	if($resizeKey!=null){
		@include(ADMIN_PATH.'include/imgSize.config.php');
		if(!defined('INC_IMG_CLASS')){
			include(WEB_CLASS_DIR.'Image.class.php');
			define('INC_IMG_CLASS','');
		}
	}
	
	if($_FILES[$_file]!=null){
		
		/*上传文件数组*/
		if(is_array($_FILES[$_file]['name'])){
			
			$returnPath = array();
			foreach($_FILES[$_file]['tmp_name'] as $k=>$tmpname){
				
				if($_FILES[$_file]['size'][$k]>0 && is_uploaded_file($tmpname)){
					
					$ext = strtolower(stripFirst(strrchr($_FILES[$_file]['name'][$k],'.'),'.'));
					if(in_array($ext,$allowFormat)){
						
						if($newName == null){	
						
							$autoName = $savePath.'/'.randStr(10,'Mixed').'.'.$ext;
							move_uploaded_file($tmpname,$autoName);
							$filePath = relativePath($autoName);
							
						}else{
							
							move_uploaded_file($tmpname,$savePath.'/'.$newName.$k.'.'.$ext);
							$filePath = relativePath($savePath.'/'.$newName.$k.'.'.$ext);
						}
						
						if($resizeKey!=null){
							if($imgSize[$resizeKey]!=null){
								
								$filename = substr($filePath,0,0-strlen(basename(ROOT.$filePath))).'re_'.basename(ROOT.$filePath);
								Image::Convert(ROOT.'./'.$filePath, ROOT.$filename, $imgSize[$resizeKey]['w'],  $imgSize[$resizeKey]['h'], Image::MODE_CUT);
								@unlink(ROOT.$filePath);
								$filePath = $filename;
							}
						}

						$returnPath[$k] = $filePath;
					}
				}
			}
			
			return $returnPath;
			
		/*单个文件上传*/
		}else{
			
			if($_FILES[$_file]['size']>0 && is_uploaded_file($_FILES[$_file]['tmp_name'])){
				
				$ext = strtolower(stripFirst(strrchr($_FILES[$_file]['name'],'.'),'.'));
				if(in_array($ext,$allowFormat)){
					
					if($newName == null){
						
						$autoName = $savePath.'/'.randStr(10,'Mixed').'.'.$ext;
						move_uploaded_file($_FILES[$_file]['tmp_name'],$autoName);
						$filePath = relativePath($autoName);
	
					}else{
						
						move_uploaded_file($_FILES[$_file]['tmp_name'],$savePath.'/'.$newName.'.'.$ext);
						$filePath = relativePath($savePath.'/'.$newName.'.'.$ext);
					}
					
					if($resizeKey!=null){
						if($imgSize[$resizeKey]!=null){
							
							$filename = substr($filePath,0,0-strlen(basename(ROOT.$filePath))).'re_'.basename(ROOT.$filePath);
							Image::Convert(ROOT.'./'.$filePath, ROOT.$filename, $imgSize[$resizeKey]['w'],  $imgSize[$resizeKey]['h'], Image::MODE_CUT);
							@unlink(ROOT.$filePath);
							$filePath = $filename;
						}
					}
					
					return $filePath;
				}
			
			}
			
		}
		
	}
	
	return '';
	
}


/**时间日期**/

/*
当前时间
@param $foramt 输出格式
@return 格式化后的当前时间,可延时为获取当前时间的年月日时分秒;
*/
function now($format=''){
	
	if($format == ''){
		return date('Y-m-d H:i:s');
	}
	
	return date($format);
}

/*
获取指定时间的年月日时分秒;
@param $time string 
@param $formateStr 格式符
@return 时间字符串
*/
function timeFormat($time,$formatStr){
	if($time==''){
		
		return now($formatStr);
		
	}else if(is_string($time)){
		
		$time = strtotime($time);
	}
	return date($formatStr,$time);	
}

/*
获取中文的星期
@param string time时间字符
*/
function getZhWeekday($time=''){
	
	$weekArray = array('日','一','二','三','四','五','六');
	return $weekArray[timeFormat($time,'w')];
}


/*
时间运算
@param time 时间字符
@param offset 时间偏移,往前或往后推多少单位
@param unit 单位值 y,m,d,h,i,s
@return 返回时间戳
*/
function dateSub($time,$offset,$unit='d'){
	
	$second = 1;
	
	if($unit == 'd'){
		
		$second = $offset*24*3600;	
		
	}else if($unit == 'm'){
		
		$second = $offset*30*24*3600;	
		
	}else if($unit == 'y'){
		
		$second = $offset*365*24*3600;		
	}else if($unit == 'h'){
		
		$second = $offset*3600;		
	}else if($unit == 'i'){
		
		$second = $offset*60;	
		
	}else if($unit == 's'){
		
		$second = $offset;		
	}	
	$time = strtotime($time);
	
	return $time+$second;
}

/*
计算两个时间的距离
@param time1 string 时间1
@param time2 string 时间2
@param unit 单位值 y,m,d,h,i,s
@return  时间
*/
function timeDistant($time1,$time2,$unit='d'){
	
	$time1 = strtotime($time1);
	$time2 = strtotime($time2);
	
	$second = 1;
	if($unit == 'd'){
		
		$second = 24*3600;	
		
	}else if($unit == 'm'){
		
		$second = 30*24*3600;	
		
	}else if($unit == 'y'){
		
		$second = 365*24*3600;		
	}else if($unit == 'h'){
		
		$second = 3600;		
	}else if($unit == 'i'){
		
		$second = 60;			
	}
	
	return abs(round(($time1-$time2)/$second,0));
		
}

/*********************
前台优化函数
**********************
*/


//动态内联文件
function loadOuterFile($file,$type,$cookie){
	if($_COOKIE[PRE.$cookie]){
		if($type=='js'){
			echo"<script src=\"$file\"  ></script>\n";
		}else if($type=='css'){
			echo "<link type=\"text/css\" rel=\"stylesheet\" href=\"$file\" />\n";
		}
	}else{
		setCookies($cookie,'yes',5);	
		if($type=='js'){
			echo "<script type=\"text/javascript\" refer>\n";
			require($file);
			echo "</script>";
		}else if($type=='css'){
			
			echo "<style>";
			require($file);
			echo "</style>";
			
		}
	}
}
/**合并外部脚本文件
 * *file 为一数组
 * $mName合并后的名字
 */
function mergeFiles($file,$mName){
	
	if($file==null || count($file)<=1){
		
		return;
	}
	
	$ext = strrchr($mName,'.');
	
	if(!file_exists($mName) ||  time()- filemtime($mName)>76400){
		
		foreach($file as $key=>$each){
			
			$merge.=file_get_contents($each)."\n";
		}
		
		$merge = $ext == '.css' ? compress($merge) :  $merge;
		file_put_contents($mName,$merge);
	}
	
	
	if($ext == '.js'){
		return "\n<script src=\"$mName\" ></script>\n";
	}else if($ext == '.css'){
		return "\n<link type=\"text/css\" rel=\"stylesheet\" href=\"$mName\" />\n";
	}
}
/**压缩脚本文件****/
function compress($content){

	$content = preg_replace('/\n+|\r+/','',$content);
	$content = preg_replace('/;\s+/',';',$content);
	$content = preg_replace('/{\s+/','{',$content);
	$content = preg_replace('/\/\*(.+?)\*\//s','',$content);
	$content = preg_replace('/}\s+/','}',$content);
	
	
	return trim($content);

}

/**压缩脚本文件****/
function compress_js($content){

	$content = preg_replace('/\/\/.+\s*/','',$content);
	$content = preg_replace('/\/\*(.+?)\*\//s','',$content);
	$content = preg_replace('/;\n+|;\r+/',';',$content);
	
	$content = preg_replace('/;\s+/',';',$content);
	
	$content = preg_replace('/\s*{\s*|{\s*/','{',$content);
	$content = preg_replace('/\)\s*{/','){',$content);
	$content = preg_replace('/\){\s*/','){',$content);
	$content = preg_replace('/\s*}else\s*{|}\s*else\s*{\s*/','}else{',$content);
	$content = preg_replace('/\s*}\s*else/','}else',$content);
	$content = preg_replace('/}\s+function/','}function',$content);
	$content = preg_replace('/}\s+}/s','}}',$content);
	$content = preg_replace('/}\s+if/','}if',$content);
	$content = preg_replace('/\s+=\s+/','=',$content);
	$content = preg_replace('/for\s+\(/','for(',$content);
	$content = preg_replace('/}\s+var/','}var',$content);
	$content = preg_replace('/}\s+var/','}var',$content);
	$content = preg_replace('/}\s+}/s','}}',$content);
	$content = preg_replace('/\s+:\s+/',':',$content);
	$content = preg_replace('/\)\s+}/',')}',$content);
	
		
	return trim($content);

}

/*
目录操作 

@param string $folder 存在的目录名称
@param $callback 在遍历时使用的函数
@return array文件结构树
*/

function scanFolderArray($folder,$callback=''){
	
	if(!file_exists($folder)){	
		return false;
	}
	
	if(is_dir($folder)){
		
		$sub = scandir($folder);
		$temp = array();
		foreach($sub as $k=>$fname){
			
			if($fname!='.' && $fname!='..'){	
				$fullName = $folder.'./'.$fname;
				if(is_dir($fullName)){						  					
					$temp[$fname] = scanFolderArray($fullName);
				}else{
					$temp[] = $fname;	
				}
				
				if(function_exists($callback)){
					$callback($fullName);	
				}
			}
		
		}
		return $temp;
	}
}

/*
从数组中创建文件结构
@param array $tree 文件结构数组
@param string $parent 父文件目录名
*/
function createFolderArray($tree,$parent){
	
	if(!is_array($tree) || $tree == null){
		return false;
	}
	
	if(!file_exists($parent)){
		mkdir($parent);
	}
	foreach($tree as $cur=>$sub){
		
		if(is_string($cur)){			
			
			if(!file_exists($parent.'/'.$cur)){
				mkdir($parent.'/'.$cur);
			}				
			if(is_array($sub) && $sub!=null){
				createFolderArray($sub,$parent.'/'.$cur);
			}
		}
	}
}

/*
复制目录
@param string $s 源目录
@param string $d 目标目录
*/
function copyDir($s,$d){
	
	if(!file_exists($s) || !file_exists($s) 
		||  !is_dir($d) || !is_dir($s)){		
		return false;
	}
	
	$sub = scandir($s);
	foreach($sub as $k=>$v){
		if($v!='.' && $v!='..'){			
			$path = $s.'/'.$v;
			if(is_dir($path)){	
				
				!file_exists($d.'/'.$v) && mkdir($d.'/'.$v);
				copyDir($path,$d.'/'.$v);	
				
			}else{
				copy($path,$d.'/'.$v);
			}
		}
	}
}

function deleteDir($dir,$delSelf=true){
	
	if(!file_exists($dir) && !is_dir($dir)){
		return false;
	}
	
	$sub = scandir($dir);
	foreach($sub as $k=>$d){
		
		if($d!='.' && $d!='..'){
			$path = $dir.'/'.$d;
			if(is_dir($path)){				
				deleteDir($path);					
			}else{
				unlink($path);
			}
		}
	}
	
	if($delSelf == true){
		rmdir($dir);
	}
}

function relativePath($path){

	if(!file_exists($path)){
		return false;
	}
	
	$path = realpath($path);
	$path = substr($path,strlen(ROOT));
	$path = str_replace('\\','/',$path);
	
	return $path;
}


/*
单位转换*/

/*
将bit转换为Mb
*/
function bitsToMb($bits){

	return round($bits/1048576,2);
}

/*
将bit转换为Kbs
*/

function bitsToKb($bits){

	return round($bits/1024,2);
}

/*
检测字符单位为bit,mb,kb
*/

function checkBitUnit($unitStr){

	if(preg_match('/^\d+M$/i',$unitStr)){
		return 'm';
	}else if(preg_match('/^\d+k$/i',$unitStr)){
		return 'k';
	}else if(preg_match('/^\d+b$/i',$unitStr)){
		return 'b';
	}
}

?>